package com.xx.jicheng.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yihang.common.util.PinyinUtil;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.xx.jicheng.entity.Category;
import com.xx.jicheng.mapper.CategoryMapper;
import com.xx.jicheng.service.CategoryService;

@Service
public class CategoryServiceImpl implements CategoryService {

	@Autowired
	private CategoryMapper categoryMapper;

	private ObjectMapper mapper = new ObjectMapper();

	@Override
	public List<Category> findAll() {
		return categoryMapper.findAll();
	}

	@Override
	public BiMap<String, String> findAttrs(String cname) {
		HashBiMap<String, String> map = HashBiMap.create();
		Category category = categoryMapper.findByName(cname);
		String cid = category.getId();
		try {
			if (cid.length() == 4) { // 二级类别
				List<Category> list = categoryMapper.findByPid(cid);
				for (Category c : list) {
					List<String> attrs = mapper.readValue(c.getAttr(), new TypeReference<List<String>>() {
					});
					for (String attr : attrs) {
						map.put(attr, PinyinUtil.getPinyin(attr));
					}
				}
			} else if (cid.length() == 6) {// 三级类别
				Category c = categoryMapper.findById(cid);
				List<String> attrs = mapper.readValue(c.getAttr(), new TypeReference<List<String>>() {
				});
				for (String attr : attrs) {
					map.put(attr, PinyinUtil.getPinyin(attr));
				}
			}
			return map;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
